from random import random
from pyppeteer import launch
import asyncio
from pymysql import *
import random
from ast import literal_eval
from regist_conf import *
from loguru import logger
from aws_ip_shifter import ElasticIPController, get_instance_id
from redis_utils import RedisFunc, RedisQueue




logger.add('regist.log', rotation="500 MB", encoding='utf-8')
instance_id = 'i-08b5e2cfff0913f85'
ip_controller = ElasticIPController(instance_id)



def pop_from_queue(queue_name='rq'):
    q = RedisQueue(queue_name, redis_conf)
    while 1:
        result = literal_eval(q.get_nowait())
        if not result:
            break
        logger.info(f"Current deal with email: {result[0]} - password: {result[1]}")
        yield result



def get_random_ua():
    return random.choice(USER_AGENTS)


def insert(table_name, field_name, field_value):

    conn = Connection(**myql_params)  # 获取连接对象
    cr_obj = conn.cursor()  # 获取cursor对象
    st = ""
    for i in field_name:
        if i == field_name[-1]:
            st += "".join(i+")")
        elif i == field_name[0]:
            st+= "".join("("+i+",")
        else:
            st += "".join(i + ",")
    field_name=st
    try:
        cr_obj.execute("insert into {}{} values{}".format(table_name, field_name, field_value))
        conn.commit()
        logger.info(f"sql - insert - sucesess ")
    except Exception as e:
        logger.info(f"sql - insert - error - reason - {e}")
        conn.rollback()
    finally:
        cr_obj.close()
        conn.close()



# 启动无痕模式
async def main():
    IP=ip_controller.change_address()
    email, passwd, code = next(pop_from_queue())
    url='https://www.pinterest.com/?en-us'
    logger.info(f'------------start regist--------------')
    logger.info(f"email: {email} - password: {passwd} - ip :{IP} - current")
    # await page_1.authenticate({username, passwd})
    agent = get_random_ua()
    # print (agent)
    launch_kwargs = {
        # 控制是否为无头模式
        "headless": True,
        # chrome启动命令行参数
        'ignoreHTTPSErrors': True,
        # 'ignoreDefaultArgs': ["--enable-automation"],
        "args": [
            '--ignore-certificate-errors',
            # 浏览器代理 配合某些中间人代理使用
            # "--proxy-server=https://%s:22225"%ip,
            # "--proxy-server=https://zproxy.lum-superproxy.io:22225",
            # 最大化窗口
            "--start-maximized",
            # 取消沙盒模式 沙盒模式下权限太小
            "--no-sandbox",
            # 不显示信息栏  比如 chrome正在受到自动测试软件的控制 ...
            "--disable-infobars",
            # log等级设置 在某些不是那么完整的系统里 如果使用默认的日志等级 可能会出现一大堆的warning信息
            "--log-level=3",
            # 设置UA
            "--user-agent={}".format(agent),
        ],
        # 用户数据保存目录 这个最好也自己指定一个目录
        # 如果不指定的话，chrome会自动新建一个临时目录使用，在浏览器退出的时候会自动删除临时目录
        # 在删除的时候可能会删除失败（不知道为什么会出现权限问题，我用的windows） 导致浏览器退出失败
        # 然后chrome进程就会一直没有退出 CPU就会狂飙到99%
        "userDataDir": "userdata",
    }

    browser = await launch(launch_kwargs)  # headless为True，不弹出浏览器，为False弹出浏览器
    context = await browser.createIncognitoBrowserContext()
    page = await context.newPage()
    await page.setViewport({"width": 1920, "height": 1080})
    await page.goto(url, timeout=0)
    # await page.evaluate('()=>{Object.defineProperties(navigator,{webdriver:{get:()=>false}})}')
    await page.evaluate(js1)
    await page.evaluate(js3)
    # await page.evaluate(js6)
    await page.evaluate(js4)
    await page.evaluate(js5)
    # await page.waitForNavigation(
    #     waitUntil="load",
    #     timeout=1000
    # )
    await page.waitFor(10000)
    try:

        button = await page.querySelector("div[data-test-id='simple-signup-button']")
        await button.click(delay=3)  # 点击注册
        await page.waitFor(1200)
        emailInputField = await page.querySelector("input[id='email']")
        await emailInputField.type(email)
        await page.waitFor(1300)
        passwordInputField = await page.querySelector("input[id='password']")
        await passwordInputField.type(passwd)
        await page.waitFor(1400)
        ageInputField = await page.querySelector("input[id='age']")
        await ageInputField.type(str(random.randint(18,35)))
        # content = await page.content()
        # if 'We could not complete that request.' in content:
        #     await page.waitFor(60000)
        #     # push_to_queue(data, queue_name='rq')
        #     continue
        registerFormSubmitButton  = await page.querySelector("div[data-test-id='registerFormSubmitButton']")
        await registerFormSubmitButton.click(delay=3)  # 点击提交
        await page.waitFor(10000)
        nux_name_done_btn = await page.querySelector("div[data-test-id='nux_name_done_btn']")
        await nux_name_done_btn.click(delay=3)  # 点击next
        await page.waitFor(5000)
        female_label = await page.querySelector("div[data-test-id='nux-gender-female-label']")
        await female_label.click(delay=3)  # 点击性别
        await page.waitFor(10000)
        await page.select('select[id="newUserLanguage"]','en-US')#选择下拉框内容
        await page.waitFor(10000)
        await page.select('select[id="newUserCountry"]', 'US')
        await page.waitFor(3000)
        country_next = await page.querySelector("div[data-test-id='nux-locale-country-next-btn']")
        await country_next.click(delay=3)
        await page.waitFor(5000)
        content_1 = await page.content()
        if 'Last step! Tell us' in content_1:
            interests  = await page.querySelectorAll("button[data-test-id='nux-picker-topic']")
            inter_list = random.sample(interests, 5)
            for I in inter_list:
                await page.waitFor(100)
                await I.click(delay=3)
            done_button = await page.querySelector("div[data-test-id='nux-picker-done-btn']")
            await page.waitFor(3000)

            await done_button.click(delay=3)
            await page.waitFor(10000)
            last_content = await page.content()
            if 'Welcome,' in last_content:
                field_name = ('pin_id', 'email', 'pwd', 'collect', 'stat', 'ip')
                field_value = (code, email, passwd, '0', '1', IP)
                insert('pinterest_account', field_name, field_value)
                logger.info(f'-----------------regist sucesess---------------------')
                logger.info(f"email: {email} - password: {passwd} - sucesess - ip :{IP}")

            else:
                logger.info(f'-----------------regist failed----------------------')
                field_name = ('pin_id', 'email', 'pwd', 'collect', 'stat', 'ip')
                field_value = (code, email, passwd, '0', '0', IP)
                insert('pinterest_err', field_name, field_value)
                logger.error(f"email: {email} - password: {passwd} - failed - ip :{IP}")
                ip_controller.rollback()
                await page.close()
                await browser.close()


        else:
            categories = await page.querySelectorAll("button[class='NuxInterest NuxInterestCategory']")  #标签
            await page.waitFor(3000)
            categorie_list = random.sample(categories, 2)
            await categorie_list[0].click(delay=3)  # 选择标签
            await categorie_list[1].click(delay=3)  # 选择标签
            await page.waitFor(1000)
            done_button = await page.querySelector("div[data-test-id='nux-picker-done-btn']")
            await done_button.click(delay=3)
            await page.waitFor(4000)
            topics  = await page.querySelectorAll("button[data-test-id='nux-picker-topic']")  #topic
            topic_list = random.sample(topics, 5)
            for t in topic_list:
                await page.waitFor(2000)
                await t.click(delay=3)

            done_button  = await page.querySelector("div[data-test-id='nux-picker-done-btn']")
            await page.waitFor(3000)
            await done_button.click(delay=3)
            await page.waitFor(10000)
            last_content_1 = await page.content()
            if  'Welcome,' in last_content_1:

                field_name=('pin_id','email','pwd','collect','stat','ip')
                field_value=(code,email,passwd,'0','1',IP)
                insert('pinterest_account',field_name,field_value)
                logger.info(f'-----------------regist sucesess---------------------')
                logger.info(f"email: {email} - password: {passwd} - sucesess - ip :{IP}")

            else:
                logger.info(f'-----------------regist failed---------------------')
                field_name = ('pin_id', 'email', 'pwd', 'collect', 'stat', 'ip')
                field_value = (code, email, passwd, '0', '0', IP)
                insert('pinterest_err', field_name, field_value)
                logger.error(f"email: {email} - password: {passwd} - failed - ip:{IP}")
                ip_controller.rollback()
                await page.close()
                await browser.close()
        ip_controller.rollback()
        await page.close()
        await browser.close()


    except Exception as e:
        logger.info(f'-----------------run error---------------------')
        field_name = ('pin_id', 'email', 'pwd', 'collect', 'stat', 'ip')
        field_value = (code, email, passwd, '0', '0', IP)
        insert('pinterest_err', field_name, field_value)
        logger.error(f"email: {email} - password: {passwd} - failed - ip:{IP} - reason :{e}")
        ip_controller.rollback()
        await page.waitFor(20000)
        await page.close()
        await browser.close()






async def run(count):
    for i in range(count):
        await main()
        # ip1 = ip_controller.change_address()
        #
        # await main(ip1)
        # ip2 = ip_controller.rollback()
        # await main(ip2)




# 启动
loop = asyncio.get_event_loop()

loop.run_until_complete(run(30))

